<template>
  <view class="container">
    <view class="header">
      <text class="title">打卡有礼</text>
      <view class="user-info-bar">
        <image class="avatar" :src="userAvatar || '/static/default-avatar.png'" />
        <text class="user-name">{{ userName || '游客' }}</text>
        <view class="points">
          <text class="points-label">积分:</text>
          <text class="points-value">{{ userPoints }}</text>
        </view>
      </view>
    </view>

    <view class="tabs">
      <view class="tab" :class="{ active: activeTab === 'list' }" @click="activeTab = 'list'">
        <text>打卡任务</text>
      </view>
      <view class="tab" :class="{ active: activeTab === 'map' }" @click="activeTab = 'map'">
        <text>景点地图</text>
      </view>
      <view class="tab" :class="{ active: activeTab === 'rewards' }" @click="activeTab = 'rewards'">
        <text>积分兑换</text>
      </view>
    </view>

    <!-- 景点地图 Tab -->
    <view v-if="activeTab === 'map'" class="tab-content">
      <map class="map" :latitude="mapCenter.latitude" :longitude="mapCenter.longitude" :markers="markers" :scale="14"
        @markertap="onMarkerTap"></map>

      <!-- 底部打卡景点信息 -->
      <view v-if="selectedSpot" class="spot-info">
        <image class="spot-image" :src="selectedSpot.imageUrl" mode="aspectFill" />
        <view class="spot-details">
          <text class="spot-name">{{ selectedSpot.name }}</text>
          <text class="spot-desc">{{ selectedSpot.description }}</text>
          <view class="spot-stats">
            <text class="spot-points">打卡得{{ selectedSpot.points }}分</text>
            <text class="spot-count">{{ selectedSpot.checkInCount }}人已打卡</text>
          </view>
        </view>
        <button class="checkin-btn" :class="{ 'checked-in': selectedSpot.isCheckedIn }" @click="checkInSpot"
          :disabled="selectedSpot.isCheckedIn">
          {{ selectedSpot.isCheckedIn ? '已打卡' : '立即打卡' }}
        </button>
      </view>
    </view>

    <!-- 打卡列表 Tab -->
    <view v-if="activeTab === 'list'" class="tab-content">
      <!-- 打卡进度条 -->
      <view class="progress-container">
        <view class="progress-header">
          <text class="progress-title">{{ topicName || '打卡进度' }}</text>
          <text class="progress-count">{{ checkedInCount }}/{{ totalSpotCount }} 完成</text>
        </view>
        <view class="progress-bar-container">
          <view class="progress-bar" :style="{ width: progressPercentage + '%' }"></view>
        </view>
        <text class="progress-desc">{{ topicDesc || '探寻莒文化历史脉络，通过莒县古城、莒县博物馆、城子崖遗址游览，感受千年文明魅力。' }}</text>
      </view>

      <scroll-view scroll-y class="spot-list">
        <view v-for="(spot, index) in spots" :key="index" class="spot-card">
          <image class="spot-card-image" :src="spot.imageUrl" mode="aspectFill" />
          <view class="spot-card-content">
            <text class="spot-card-name">{{ spot.name }}</text>
            <text class="spot-card-desc">{{ spot.description }}</text>
            <view class="spot-card-footer">
              <text class="spot-card-points">{{ spot.points }}积分</text>
              <button class="spot-card-btn" :class="{ 'checked-in': spot.isCheckedIn }"
                @click="spot.isCheckedIn ? null : selectSpot(spot)">
                {{ spot.isCheckedIn ? '已打卡' : '去打卡' }}
              </button>
            </view>
          </view>
        </view>
      </scroll-view>

    </view>

    <!-- 积分兑换 Tab -->
    <view v-if="activeTab === 'rewards'" class="tab-content">
      <scroll-view scroll-y class="rewards-list">
        <view v-for="(reward, index) in rewards" :key="index" class="reward-card">
          <image class="reward-image" :src="reward.imageUrl" mode="aspectFill" />
          <view class="reward-content">
            <text class="reward-name">{{ reward.name }}</text>
            <text class="reward-desc">{{ reward.description }}</text>
            <view class="reward-footer">
              <text class="reward-points">{{ reward.points }}积分</text>
              <button class="reward-btn" @click="redeemReward(reward)" :disabled="userPoints < reward.points">
                {{ userPoints >= reward.points ? '立即兑换' : '积分不足' }}
              </button>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 打卡成功弹窗 -->
    <view class="modal" v-if="showSuccessModal">
      <view class="modal-content">
        <image class="success-icon" src="/static/images/success.png" />
        <text class="modal-title">打卡成功</text>
        <text class="modal-text">恭喜获得 {{ selectedSpot ? selectedSpot.points : 0 }} 积分</text>
        <button class="modal-btn" @click="closeSuccessModal">确定</button>
      </view>
    </view>

    <!-- 打卡失败弹窗 -->
    <view class="modal" v-if="showErrorModal">
      <view class="modal-content">
        <image class="error-icon" src="/static/images/error.png" />
        <text class="modal-title">打卡失败</text>
        <text class="modal-text">{{ errorMessage }}</text>
        <button class="modal-btn" @click="closeErrorModal">确定</button>
      </view>
    </view>
  </view>
</template>

<script>
import { useAuthStore } from '@/stores/auth'
import { http } from '@/api/request'
import { defaultThemes, defaultRewards, defaultSpots } from './data'

export default {
  data() {
    return {
      activeTab: 'list',
      userAvatar: '',
      userName: '',
      userPoints: 120,
      mapCenter: {
        latitude: 35.58,
        longitude: 118.84
      },
      selectedSpot: null,
      showSuccessModal: false,
      showErrorModal: false,
      errorMessage: '',
      spots: [], // Now an empty array that will be populated from API
      topicName: '',
      topicDesc: '',
      topic: '', // Add this property to store the current topic
      totalSpotCount: 0,
      awardPoints: 0,
      completionRate: 0,
      rewards: defaultRewards, // Use imported rewards from data.js
      defaultSpots: defaultSpots, // Use imported spots from data.js
      themeId: '', // Add this property to store the current theme ID
    };
  },
  computed: {
    markers() {
      return this.spots.map(spot => ({
        id: spot.id,
        latitude: spot.latitude,
        longitude: spot.longitude,
        title: spot.name,
        width: 30,
        height: 30,
        callout: {
          content: spot.name,
          color: '#000000',
          fontSize: 12,
          borderRadius: 4,
          padding: 5,
          bgColor: '#ffffff',
          display: 'ALWAYS'
        }
      }));
    },
    checkedInCount() {
      return this.spots.filter(spot => spot.isCheckedIn).length;
    },
    progressPercentage() {
      // Use the completion rate from API if available, otherwise calculate from spots
      if (this.completionRate !== undefined) {
        return this.completionRate * 100;
      }
      return this.totalSpotCount > 0 ? Math.round((this.checkedInCount / this.totalSpotCount) * 100) : 0;
    }
  },
  onLoad(options) {
    // Get theme parameter from URL if available
    if (options && options.theme) {
      this.topic = decodeURIComponent(options.theme);
    }
    
    // Get themeId parameter from URL if available
    if (options && options.themeId) {
      this.themeId = options.themeId;
    }
    
    this.getUserInfo();
    this.getLocation();
    this.fetchSpots();
  },
  methods: {
    getUserInfo() {
      const authStore = useAuthStore();
      if (authStore.userInfo) {
        this.userAvatar = authStore.userInfo.avatarUrl;
        this.userName = authStore.userInfo.nickName;
      }
    },
    getLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.mapCenter.latitude = res.latitude;
          this.mapCenter.longitude = res.longitude;
        },
        fail: (err) => {
          console.error('获取位置失败', err);
        }
      });
    },
    fetchSpots() {
      // Get necessary parameters
      const authStore = useAuthStore();
      const userId = authStore.isLoggedIn ? (authStore.userInfo.openId || '123456') : '123456';
      const userTopicId = this.themeId || '1'; // Use themeId from URL or default to '1'
      
      // Call the API endpoint with the correct parameters
      const url = `/ju/gis/map/scenic_check/list?user_id=${encodeURIComponent(userId)}&user_topic_id=${encodeURIComponent(userTopicId)}`;
      
      http.get(url)
        .then(httpRes => {
          const res = httpRes.data || {};
          if (res.code === 0 && res.data) {
            const apiData = res.data;
            
            // Store topic information
            this.topicName = apiData.topic || '打卡任务';
            this.topicDesc = apiData.topic_desc || '';
            this.completionRate = apiData.completion_rate || 0;
            this.awardPoints = parseInt(apiData.award_points || 0);
            
            // Process checked and unchecked spots
            const checkedSpots = apiData.task_checked_scenic || [];
            const todoSpots = apiData.todo_task_check || [];
            const uncheckedSpots = apiData.no_task_checked_scenic || [];
            
            // Calculate total spots
            this.totalSpotCount = apiData.routes_contain_all_scenic_counts || 
                                 (checkedSpots.length + todoSpots.length);
            
            // Update user points from API if available
            if (apiData.use_completed_sum_points) {
              this.userPoints = parseInt(apiData.use_completed_sum_points);
            }
            
            // Combine all spots for display
            const allSpots = [
              ...this.processSpots(checkedSpots, true),
              ...this.processSpots(todoSpots, false),
              ...this.processSpots(uncheckedSpots, false, false) // These are not part of the main task
            ];
            
            // Sort spots by checked-in status (checked first)
            this.spots = allSpots.sort((a, b) => {
              if (a.isCheckedIn === b.isCheckedIn) return 0;
              return a.isCheckedIn ? -1 : 1;
            });
            
            // Set map center to the first spot if spots are available
            if (this.spots.length > 0) {
              this.mapCenter = {
                latitude: this.spots[0].latitude,
                longitude: this.spots[0].longitude
              };
            }
            
            console.log('Loaded spots:', this.spots.length);
          } else {
            console.error('Invalid API response structure:', res);
            this.loadDefaultSpots();
            uni.showToast({
              title: '加载默认打卡点',
              icon: 'none'
            });
          }
        })
        .catch(err => {
          console.error('获取打卡点失败:', err);
          this.loadDefaultSpots();
          uni.showToast({
            title: '加载默认打卡点',
            icon: 'none'
          });
        });
    },
    
    // Helper method to process spots from API response
    processSpots(spotsArray, isCheckedIn, isPartOfTask = true) {
      return spotsArray.map((spot, index) => {
        return {
          id: spot.scenic_id || (Date.now() + index), // Use scenic_id if available or generate unique ID
          name: spot.scenic_name,
          description: spot.scenic_desc,
          points: parseInt(spot.scenic_points || 0),
          latitude: parseFloat(spot.scenic_latitude || spot.latitude),
          longitude: parseFloat(spot.scenic_longitude || spot.longitude),
          imageUrl: spot.image_url,
          checkInCount: parseInt(spot.check_in_count || 0),
          isCheckedIn: isCheckedIn,
          isPartOfTask: isPartOfTask // Flag to indicate if this is part of the main task
        };
      });
    },

    loadDefaultSpots() {
      // 加载默认的打卡点
      this.spots = [...this.defaultSpots];

      // 设置地图中心为第一个默认打卡点
      if (this.spots.length > 0) {
        this.mapCenter = {
          latitude: this.spots[0].latitude,
          longitude: this.spots[0].longitude
        };
      }

      console.log('已加载默认打卡点');
    },
    fetchCheckedInStatus() {
      const authStore = useAuthStore();
      const userId = authStore.isLoggedIn ? (authStore.userInfo.openId || '123456') : '123456';
      const userTopicId = this.themeId || '1'; // Use themeId from URL or default to '1'

      const url = `/ju/gis/map/scenic_check/list?user_id=${encodeURIComponent(userId)}&user_topic_id=${encodeURIComponent(userTopicId)}`;

      // Call the API to get checked-in status
      http.get(url)
        .then(httpRes => {
          const res = httpRes.data || {};
          if (res.code === 0 && res.data) {
            // Process completed spots
            const checkedSpots = res.data.task_checked_scenic || [];

            // Create a map of spot IDs to checked status
            const checkedSpotsMap = {};
            checkedSpots.forEach(spot => {
              checkedSpotsMap[spot.scenic_id] = true;
            });

            // Update existing spots with checked-in status
            this.spots.forEach(spot => {
              if (checkedSpotsMap[spot.id]) {
                spot.isCheckedIn = true;
              }
            });

            // If the selected spot exists and is in the checked spots, update its status
            if (this.selectedSpot && checkedSpotsMap[this.selectedSpot.id]) {
              this.selectedSpot.isCheckedIn = true;
            }

            console.log('Checked-in status updated with completion rate:', res.data.completion_rate);
          } else {
            console.error('Invalid API response for checked-in status:', res);
          }
        })
        .catch(err => {
          console.error('Failed to fetch checked-in status:', err);
        });
    },
    onMarkerTap(e) {
      const spotId = e.markerId;
      this.selectedSpot = this.spots.find(spot => spot.id === spotId);
    },
    selectSpot(spot) {
      this.selectedSpot = spot;

      if (this.activeTab === 'list') {
        this.activeTab = 'map';
        this.mapCenter = {
          latitude: spot.latitude,
          longitude: spot.longitude
        };
      }
    },
    checkInSpot() {
      // 检查用户是否已经登录
      const authStore = useAuthStore();
      if (!authStore.isLoggedIn) {
        this.showErrorModal = true;
        this.errorMessage = '请先登录后再打卡';
        return;
      }

      // 检查是否已经打卡过
      if (this.selectedSpot.isCheckedIn) {
        this.showErrorModal = true;
        this.errorMessage = '您已经在该景点打卡过了';
        return;
      }
      
      // Check if user is close enough to the spot (can be implemented based on your requirements)
      const spotLat = this.selectedSpot.latitude;
      const spotLng = this.selectedSpot.longitude;
      const userLat = this.mapCenter.latitude;
      const userLng = this.mapCenter.longitude;
      
      const distance = this.calculateDistance(spotLat, spotLng, userLat, userLng);
      const maxDistance = 0.5; // 500 meters in km
      
      if (distance > maxDistance) {
        this.showErrorModal = true;
        this.errorMessage = `您距离打卡点太远（${Math.round(distance * 1000)}米），请靠近后再试`;
        return;
      }
      
      this.doCheckIn();
    },
    doCheckIn() {
      // 获取必要的参数
      const authStore = useAuthStore();
      const userId = authStore.isLoggedIn ? (authStore.userInfo.openId || '123456') : '123456';
      const topicId = this.themeId || '1';
      const scenicId = this.selectedSpot.id;
      const scenicComment = `我在${this.selectedSpot.name}打卡了，非常推荐！`;
      
      // 使用封装的请求方法，注意API参数要放在URL的query string中
      http.post(`/ju/gis/map/checking?user_id=${encodeURIComponent(userId)}&topic_id=${encodeURIComponent(topicId)}&scenic_id=${encodeURIComponent(scenicId)}&scenic_comment=${encodeURIComponent(scenicComment)}&user_lat=${this.mapCenter.latitude}&user_lng=${this.mapCenter.longitude}&distance=500`, 
      {}) // Empty body since all parameters are in the query string
        .then(res => {
          // 更新本地数据
          const index = this.spots.findIndex(spot => spot.id === this.selectedSpot.id);
          if (index !== -1) {
            this.spots[index].isCheckedIn = true;
            this.spots[index].checkInCount++;
            this.selectedSpot = this.spots[index];
            
            // Update completed count and check if all tasks are completed
            if (this.spots[index].isPartOfTask) {
              this.checkedInCount++;
              
              // Check if all tasks are completed
              if (this.checkedInCount >= this.totalSpotCount) {
                this.completionRate = 1;
                this.userPoints += this.awardPoints; // Add bonus points for completing all tasks
              }
            }
          }

          // 增加用户积分
          this.userPoints += this.selectedSpot.points;

          // 显示成功提示
          this.showSuccessModal = true;
          
          // Refresh the spots list after check-in
          this.fetchSpots();
        })
        .catch(err => {
          console.error('打卡请求失败:', err);
          this.errorMessage = err.message || '打卡失败，请稍后再试';
          this.showErrorModal = true;
        });
    },
    redeemReward(reward) {
      if (this.userPoints < reward.points) {
        this.showErrorModal = true;
        this.errorMessage = '积分不足，无法兑换';
        return;
      }

      // TODO: 发送兑换请求到服务器

      // 更新积分
      this.userPoints -= reward.points;

      uni.showToast({
        title: '兑换成功',
        icon: 'success'
      });
    },
    closeSuccessModal() {
      this.showSuccessModal = false;
    },
    closeErrorModal() {
      this.showErrorModal = false;
      this.errorMessage = '';
    },
    calculateDistance(lat1, lon1, lat2, lon2) {
      // 将角度转换为弧度
      const toRadians = (deg) => deg * Math.PI / 180;

      // 地球半径（单位：km）
      const R = 6371;

      // 计算纬度和经度的差值
      const dLat = toRadians(lat2 - lat1);
      const dLon = toRadians(lon1 - lon2);

      // 应用 Haversine 公式
      const a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      const distance = R * c; // 距离，单位：km

      return distance;
    }
  }
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f0e3;
}

.header {
  padding: 20px;
  background-color: #d9b38c;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.user-info-bar {
  display: flex;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.user-name {
  font-size: 16px;
  color: #333;
  margin-right: 15px;
}

.points {
  display: flex;
  align-items: center;
  background-color: #f8f0e3;
  padding: 3px 10px;
  border-radius: 15px;
}

.points-label {
  font-size: 14px;
  color: #8b6b4a;
  margin-right: 5px;
}

.points-value {
  font-size: 16px;
  color: #8b6b4a;
  font-weight: bold;
}

.tabs {
  display: flex;
  background-color: #ffffff;
  padding: 2px;
  border-radius: 10px;
  margin: 10px 15px;
  overflow: hidden;
}

.tab {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px 0;
  position: relative;
}

.tab.active {
  background-color: #e8d0b5;
  border-radius: 8px;
}

.tab text {
  font-size: 14px;
  color: #333;
}

.tab-content {
  flex: 1;
  position: relative;
  margin: 0 15px 15px;
  overflow: hidden;
  border-radius: 12px;
}

.map {
  width: 100%;
  height: 100%;
  border-radius: 12px;
}

.spot-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-radius: 12px 12px 0 0;
  padding: 15px;
  display: flex;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.spot-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  margin-right: 10px;
}

.spot-details {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.spot-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.spot-desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.spot-stats {
  display: flex;
  justify-content: space-between;
}

.spot-points {
  font-size: 12px;
  color: #8b6b4a;
}

.spot-count {
  font-size: 12px;
  color: #999;
}

.checkin-btn {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  background-color: #8b6b4a;
  color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10px;
  font-size: 14px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.checkin-btn.checked-in {
  background-color: #ccc;
  color: #666;
}

.spot-list {
  height: calc(100% - 140px);
  padding: 10px 0;
}

.rewards-list {
  height: 100%;
  padding: 10px 0;
}

.spot-card,
.reward-card {
  background-color: #ffffff;
  border-radius: 10px;
  margin-bottom: 15px;
  overflow: hidden;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.spot-card-image,
.reward-image {
  width: 100%;
  height: 150px;
}

.spot-card-content,
.reward-content {
  padding: 12px;
}

.spot-card-name,
.reward-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.spot-card-desc,
.reward-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  line-height: 1.4;
}

.spot-card-footer,
.reward-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.spot-card-points,
.reward-points {
  font-size: 14px;
  color: #8b6b4a;
  font-weight: bold;
}

.spot-card-btn,
.reward-btn {
  padding: 6px 15px;
  background-color: #8b6b4a;
  color: #ffffff;
  border-radius: 20px;
  font-size: 14px;
}

.spot-card-btn.checked-in {
  background-color: #ccc;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  width: 70%;
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.success-icon,
.error-icon {
  width: 60px;
  height: 60px;
  margin-bottom: 15px;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.modal-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
  text-align: center;
}

.modal-btn {
  width: 120px;
  padding: 8px 0;
  background-color: #8b6b4a;
  color: #ffffff;
  border-radius: 20px;
  font-size: 14px;
}

.progress-container {
  background-color: #ffffff;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.progress-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.progress-count {
  font-size: 14px;
  color: #666;
}

.progress-bar-container {
  height: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 15px;
}

.progress-bar {
  height: 100%;
  background-color: #3b82f6;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.progress-text {
  font-size: 12px;
  color: #666;
  text-align: center;
}

.progress-desc {
  font-size: 12px;
  color: #666;
  text-align: center;
}
</style>
